import React, { useEffect, useState } from "react";
import "../componentsCss/comments.css";
import Cookies from "js-cookie";
import axios from "axios";

function CommentSection() {
  const [comments, setComments] = useState([]);
  const [newComment, setNewComment] = useState("");

  useEffect(() => {
    const fetchComments = async () => {
      const token = Cookies.get("token");
      try {
        // 获取一级评论
        const response = await axios.get(
          "http://localhost:8080/video/comments",
          {
            params: {
              token: token,
              videoId: "1",
            },
          }
        );

        const primaryComments = response.data.data;

        // 获取每个一级评论的二级评论
        const secondaryCommentsPromises = primaryComments.map((comment) =>
          axios.get("http://localhost:8080/video/secendcomments", {
            params: {
              token: token,
              videoId: "1",
              commentId: "1",
            },
          })
        );

        const secondaryCommentsResponses = await Promise.all(
          secondaryCommentsPromises
        );

        // 将二级评论添加到一级评论中
        const commentsWithReplies = primaryComments.map((comment, index) => ({
          ...comment,
          replies: secondaryCommentsResponses[index].data.data,
        }));

        setComments(commentsWithReplies);
      } catch (error) {
        console.error("Error fetching comments:", error);
      }
    };

    fetchComments();
  }, []);

  const handleAddComment = async () => {
    const token = Cookies.get("token");
    if (!newComment.trim()) {
      return;
    }

    try {
      const response = await axios.post(
        "http://localhost:8080/video/addcomment",
        {
          videoId: "1",
          content: newComment,
        },
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      const addedComment = response.data.data;
      setComments([...comments, addedComment]);
      setNewComment("");
    } catch (error) {
      console.error("Error adding comment:", error);
    }
  };

  return (
    <div className="comments-section">
      {comments.map((comment) => (
        <div key={comment.comment.id} className="comment">
          <p>{comment.comment.content}</p>
          <p>Author: {comment.author.name}</p>
          {comment.replies && comment.replies.length > 0 && (
            <div className="replies">
              {comment.replies.map((reply) => (
                <div key={reply.comment.id} className="reply">
                  <p>{reply.comment.content}</p>
                  <p>Author: {reply.author.name}</p>
                </div>
              ))}
            </div>
          )}
        </div>
      ))}
      <div className="add-comment">
        <textarea
          value={newComment}
          onChange={(e) => setNewComment(e.target.value)}
          placeholder="Add a comment..."
        />
        <button onClick={handleAddComment}>Submit</button>
      </div>
    </div>
  );
}

export default CommentSection;
